package com.myapp.web.struts2.validators;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator;

public class AssociationFieldValidator extends StringLengthFieldValidator {

	private String linkField;
		
	private boolean required = false;
	
	private boolean mismatch = false;
	
	private String mismatchMessage;
	
	@Override
	public void validate(Object object) throws ValidationException {
	    String fieldName = getFieldName();
        String val = (String) getFieldValue(fieldName, object);
        String val2= (String) getFieldValue(linkField, object);
        
        if (val == null || val.length() == 0 || required ) {
        	addFieldError(fieldName, object);
            // use a required validator for these
            return;
        }
             
        if ((getMinLength() > -1) && (val.trim().length() < getMinLength())) {
            addFieldError(fieldName, object);
            return ;
        } else if ((getMaxLength() > -1) && (val.trim().length() > getMaxLength())) {
            addFieldError(fieldName, object);
            return ;
        }
        if(!val.trim().equals(val2))
        {
        	mismatch = true;
        	addFieldError(fieldName, object);
        }
	}

	@Override
	public String getMessage(Object object)
	{
		if(mismatch && ! mismatchMessage.isEmpty())
		{
			return mismatchMessage;
		}
		return super.getMessage(object);
	}
	
	public boolean isRequired() {
		return required;
	}

	public void setRequired(boolean required) {
		this.required = required;
	}

	public String getLinkField() {
		return linkField;
	}

	public void setLinkField(String linkField) {
		this.linkField = linkField;
	}

	public String getMismatchMessage() {
		return mismatchMessage;
	}

	public void setMismatchMessage(String mismatchMessage) {
		this.mismatchMessage = mismatchMessage;
	}	
}
